// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// W [author] rhyme_lph
// h [email]  rhymelph@gmail.com
// Q [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/bank_reconciliation_entity.dart';
import 'package:finance_app/src/entities/bank_reconciliation_record_entity.dart';
import 'package:finance_app/src/provider/all_reports/bank_reconciliation/bank_reconciliation_detail_with_file_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/common/normal_table_pro.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/down_button_form.dart';
import 'package:finance_app/src/widgets/list_item/reconcile_list_item.dart';
import 'package:flutter/material.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "bankReconciliationDetailWithFilePage")
class BankReconciliationDetailWithFilePage extends StatefulWidget {
  final BankReconciliationEntity bank;
  final String title;
  final String closingDate;

  const BankReconciliationDetailWithFilePage({
    Key key,
    this.bank,
    this.title,
    this.closingDate,
  }) : super(key: key);

  @override
  _BankReconciliationRecordPageState createState() =>
      _BankReconciliationRecordPageState();
}

class _BankReconciliationRecordPageState
    extends State<BankReconciliationDetailWithFilePage>
    with
        PagePresenter<BankReconciliationDetailWithFilePage,
            BankReconciliationDetailWithFileProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: widget.title,
      );

  @override
  void initState() {
    provider.closingDate = widget.closingDate;
    provider.bank = widget.bank;
    provider.id = widget.bank.id;
    provider.realDifference = widget.bank.difference;
    provider.title = widget.title;
    super.initState();
  }

  @override
  Widget get buildEmptyWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                buildHasFileTopWidget(),
                Expanded(child: super.buildEmptyWidget),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  @override
  Widget get buildWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                buildHasFileTopWidget(),
                AppSpaces.grayH6,
                Expanded(
                  child: listBuilder<List<BankReconciliationRecordEntity>>(
                    selector: (_, __) => List.from(__.filterList),
                    builder: (BuildContext context,
                            List<BankReconciliationRecordEntity> value,
                            Widget child) =>
                        value.length == 0
                            ? super.buildEmptyWidget
                            : ListView.separated(
                                itemBuilder: _buildFileItems,
                                itemCount: value.length + 1,
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return AppSpaces.grayH6;
                                },
                              ),
                  ),
                ),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  Container _buildBankTitleBar({String statementBalance, String difference}) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: getDp(25), vertical: getDp(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                S.current.statement_balance,
                style: TextStyle(
                  color: aceDarkGrayColor,
                  fontSize: getSp(16),
                  fontWeight: FontWeight.w400,
                  height: 1,
                ),
              ),
              SizedBox(
                height: getDp(6),
              ),
              Text(
                statementBalance,
                style: TextStyle(
                  color: aceBlackColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 1,
                ),
              ),
            ],
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                S.current.difference,
                style: TextStyle(
                  color: aceDarkGrayColor,
                  fontSize: getSp(16),
                  fontWeight: FontWeight.w400,
                  height: 1,
                ),
              ),
              SizedBox(
                height: getDp(6),
              ),
              Text(
                difference,
                style: TextStyle(
                  color: aceBlackColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 1,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget buildHasFileTopWidget() => Column(
        children: [
          listBuilder<Tuple2<String, String>>(
            selector: (_, __) =>
                Tuple2(widget.bank.statementBalance, __.realDifference),
            builder: (BuildContext context, Tuple2<String, String> value,
                    Widget child) =>
                _buildBankTitleBar(
              statementBalance: "SGD ${value.item1}",
              difference: "SGD ${value.item2}",
            ),
          ),
          NormalTableProTitleItem(
            title: S.current.bank_records,
            padding: EdgeInsets.symmetric(
              horizontal: getDp(25),
              vertical: getDp(5),
            ),
          ),
          AppSpaces.h20,
          Row(
            children: [
              listBuilder<String>(
                selector: (_, __) => __.showStatus,
                builder: (BuildContext context, String value, Widget child) =>
                    DownButtonForm(
                  title: LanguageUtils.translateStatus(value),
                  onTap: provider.onChangeStatus,
                ),
              )
            ],
          ),
          AppSpaces.h20,
        ],
      );

  Widget _buildFileItems(BuildContext context, int index) {
    if (provider.filterList.length == index) return Container();
    return listBuilder<BankReconciliationRecordEntity>(
      selector: (_, __) => __.filterList[index],
      builder: (BuildContext context, BankReconciliationRecordEntity value,
              Widget child) =>
          ReconcileListItem(
        onTap: () => provider.onDetail(value),
        name: value.bankTransactionName,
        code: value.bankTransactionNumber,
        datetime: DateTimeUtils.formatDateTimeString(value.createdAt, true),
        status:
            value.status == 'open' ? S.current.unmatched : S.current.matched,
        amount: value.total,
      ),
    );
  }

  Widget _buildBottomBar() => Positioned(
        bottom: MediaQuery.of(context).padding.bottom + getDp(32),
        left: 0,
        right: 0,
        child: Center(
          child: listBuilder<bool>(
            selector: (_, __) => __.canReconcile,
            builder: (BuildContext context, bool value, Widget child) =>
                NormalFloatTextButton(
              title: S.current.reconcile,
              onTap: value == true ? provider.onReconcile : null,
            ),
          ),
        ),
      );
}
